package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse


/**
 * E家安康-非车投保信息回写接口
 * 陶豪
 */
public  class apiEFamilyInformation implements  ServiceBackInvoke{
    private static final Log log= LogFactory.getLog(apiEFamilyInformation.class);


    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {

        httpServletResponse.setCharacterEncoding("UTF-8");
        //初始化返回参数
        JSONObject result =new JSONObject();
        //获取接口调用方式及参数
        String GetMethod=httpServletRequest.getMethod();
        log.debug("[GetMethod]:"+GetMethod);

        String inData="";
        if (GetMethod.equals("GET")){
            inData=httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]"+inData);
        }else {
            InputStreamReader reader=new InputStreamReader(httpServletRequest.getInputStream(),"UTF-8");
            BufferedReader iny=new BufferedReader(reader);
            String line;
            while ((line=iny.readLine())!=null){
                inData+=line;
            }
            log.debug("[原始Post请求参数：]"+inData);

        }
        log.debug("[调用请求信息：]"+inData)

        if (KHUtil.isNull(inData)){
            log.debug("入参为空-无法完成操作！");
            result.put("code",-2)
            result.put("message","入参为空-无法完成操作！")

            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'apiEFamilyInformation','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
            eliteBean.update(insertSQL2,'dataSource');


            return  result.toString();
        }


        try {
            //解析Json
            JSONObject inJson =JSONObject.fromObject(inData);

            def orderNo=GetJV(inJson,"orderNo");//合作方订单申请号，系统做幂等校验  -必填
            def agencyCode=GetJV(inJson,"agencyCode");//商户号   -必填
            def productCode=GetJV(inJson,"productCode");//产品代码  -必填
            def businessType=GetJV(inJson,"businessType");//业务类型  -必填
            def transTime=GetJV(inJson,"transTime");//发送时间     -必填
            def staffid=GetJV(inJson,"staffId");//坐席工号          -必填
            def rolegroupid=GetJV(inJson,"rolegroupId");//坐席组别          -必填
            def tpiChannel=GetJV(inJson,"tpiChannel");//渠道小类    -必填
            def companycode =GetJV(inJson,"companyCode");// 机构代码   -必填
            def InsuranceConfirmLinkView =GetJV(inJson,"InsuranceConfirmLinkView");// 用户投保确认链接-查看页面   -必填
            def InsuranceConfirmLinkEdit =GetJV(inJson,"InsuranceConfirmLinkEdit");// 用户投保确认链接-编辑页面   -必填
            //投保人信息
            def appliType=GetJV(inJson,"appliType");//投保人类型     -必填
            def appliName=GetJV(inJson,"appliName");//投保人名称     -必填
            def identifyType=GetJV(inJson,"identifyType");//证件类型 -必填
            def identifyNumber=GetJV(inJson,"identifyNumber");//证件号码 -必填
            def sex=GetJV(inJson,"sex");//性别        -必填
            def birthDate=GetJV(inJson,"birthDate");//出生日期 -必填
            def mobilePhone=GetJV(inJson,"mobilePhone");//手机号码  -必填

            //被保险人信息

            def insuredName=GetJV(inJson,"insuredName");//被保险人名称  -必填
            def insuredType=GetJV(inJson,"insuredType");//被保险人类型  -必填
            def insuredidentifyType=GetJV(inJson,"insuredidentifyType");//证件类型  -必填
            def insuredidentifyNumber=GetJV(inJson,"insuredidentifyNumber");//证件号码  -必填
            def insuredsex=GetJV(inJson,"insuredsex");//被保险人性别  -必填
            def insuredbirthDate=GetJV(inJson,"insuredbirthDate");//被保险人出生日期 -必填
            def insuredappliRelation=GetJV(inJson,"insuredappliRelation");//关系代码







            //方案信息(project)
            def startDate=GetJV(inJson,"startDate");//起保日期  -必填
            def projectCode=GetJV(inJson,"projectCode");//方案代码 -必填
            def projectName=GetJV(inJson,"projectName");//方案名称  -必填
            def uwCount=GetJV(inJson,"uwCount")//投保份数   -必填
            def operateDate=GetJV(inJson,"operateDate");//投保日期  -必填
            def endDate=GetJV(inJson,"endDate");//终保日期  -必填
            def sumPremium=GetJV(inJson,"sumPremium");//总保费  -必填
            def sumInsured=GetJV(inJson,"sumInsured");//总保额  -必填
            def rec_guid=GetJV(inJson,"rec_Guid");//主键标识



            //20230907  新增13个字段传值
            def travelArea=GetJV(inJson,"travelArea");//旅行行程
            def buildingAddress=GetJV(inJson,"buildingAddress");//房屋地址
            def carOwner="";//车主姓名
            def carIdentifyType="";//车主证件类型
            def carIdentifyNumber="";//车主证件号码
            def licenseNo="";//车牌号码
            def seatCount="";//核定座位数
            def brandName="";//品牌型号
            def FieldBH="";//产品型号
            def frameNo="";//车架号
            def singeinDate="";//登记日期
            def carValue="";//车辆购置价格
            def useNature="";//车辆性质

            JSONArray batcharr;

             if(businessType.equals("proposalBatchResult")){
                 String   relist=GetJV(inJson,"itemExList");
                 JSONObject json1=JSONObject.fromObject(relist);
                  carOwner=GetJV(json1,"owner");//车主姓名
                  carIdentifyType=GetJV(json1,"identifyType");//车主证件类型
                  carIdentifyNumber=GetJV(json1,"identifyNumber");//车主证件号码
                  licenseNo=GetJV(json1,"licenseNo");//车牌号码
                  seatCount=GetJV(json1,"seatCount");//核定座位数
                  brandName=GetJV(json1,"brandName");//品牌型号
                  FieldBH=GetJV(json1,"FieldBH");//产品型号
                  frameNo=GetJV(json1,"frameNo");//车架号
                  singeinDate=GetJV(json1,"singeinDate");//登记日期
                  carValue=GetJV(json1,"carValue");//车辆购置价格
                  useNature=GetJV(json1,"useNature");//车辆性质
                  buildingAddress=GetJV(json1,"buildingAddress");//房屋地址
                  batcharr =inJson.getJSONArray("proposalList");
             }





            //校验参数是否必填
         String dealmsg=
                  KHUtil.isNullMSG("orderNo",orderNo)+
                  KHUtil.isNullMSG("agencyCode",agencyCode)+
                  KHUtil.isNullMSG("productCode",productCode)+
                  KHUtil.isNullMSG("businessType",businessType) +
                  KHUtil.isNullMSG("transTime",transTime)+
                  KHUtil.isNullMSG("staffid",staffid)+
                  KHUtil.isNullMSG("appliType",appliType)+
                  KHUtil.isNullMSG("appliName",appliName)+
                  KHUtil.isNullMSG("identifyType",identifyType)+
                  KHUtil.isNullMSG("identifyNumber",identifyNumber)+
                  KHUtil.isNullMSG("insuredName",insuredName)+
                  KHUtil.isNullMSG("insuredType",insuredType)+
                  KHUtil.isNullMSG("mobilePhone",mobilePhone)+
                  KHUtil.isNullMSG("insuredidentifyType",insuredidentifyType)+
                  KHUtil.isNullMSG("insuredidentifyNumber",insuredidentifyNumber)+
                  KHUtil.isNullMSG("insuredappliRelation",insuredappliRelation)+
                  KHUtil.isNullMSG("startDate",startDate)+
                  KHUtil.isNullMSG("projectCode",projectCode)+
                  KHUtil.isNullMSG("projectName",projectName)+
                  KHUtil.isNullMSG("uwCount",uwCount)+
                  KHUtil.isNullMSG("operateDate",operateDate)+
                  KHUtil.isNullMSG("endDate",endDate) +
                  KHUtil.isNullMSG("sumPremium",sumPremium) +
                  KHUtil.isNullMSG("sumInsured",sumInsured)+
                  KHUtil.isNullMSG("tpiChannel",tpiChannel)+
                  KHUtil.isNullMSG("rolegroupid",rolegroupid)+
                  KHUtil.isNullMSG("companycode",companycode)+
                  KHUtil.isNullMSG("InsuranceConfirmLinkView",InsuranceConfirmLinkView)+
                  KHUtil.isNullMSG("InsuranceConfirmLinkEdit",InsuranceConfirmLinkEdit)+
                  KHUtil.isNullMSG("rec_guid",rec_guid)
            ;

            if(!KHUtil.isNull(dealmsg))
            {
                log.debug("请求入参为空-请检查请求报文:"+dealmsg);
                result.put("code",-2);
                result.put("message","请求入参为空-请检查请求报文！,"+dealmsg);
                def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiEFamilyInformation','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
                eliteBean.update(insertSQL2,'dataSource');

                return  result.toString();
            }

            JdbcTemplate jt =new JdbcTemplate(eliteBean.getDataSource());
            //查询订单号是否已经在电销存在

            String dealSql="Select orderNo from EFAMILYINFORMATION where rec_guid='"+rec_guid+"'";
            def dealList=eliteBean.chaxun_sql(dealSql,"dataSource");
            //存在则修改
            if (dealList.size()>0){

                if(businessType.equals("proposalBatchResult")) {

                    String DSql='''
                              DELETE FROM E_INSURERESULT_LIST WHERE BATCH_GUID=?
                                 ''';
                    jt.update(DSql,rec_guid);

                    for (int b = 0; b < batcharr.size(); b++) {
                        JSONObject dataJson = batcharr.getJSONObject(b);
                        String proposalNo = GetJV(dataJson, "proposalNo");

                        String insertSql2 = '''
                                  INSERT INTO
                                 E_INSURERESULT_LIST
                                (rec_guid,
                                ORDERNO,
                                PROPOSALNO,
                                CREATEDDATE,
                                UPDATEDDATE,
                                batch_guid
                                )values(
                                sysguid,
                                ?,
                                ?,
                                sysdate,
                                sysdate,
                                ?
                                )
                                      ''';
                        jt.update(insertSql2, orderNo, proposalNo,rec_guid);

                    }

                }




                //修改之前,先插入历史表
                String insertHisSql='''
                                INSERT INTO
                                 EFAMILYINFORMATION_HIS
                                (
                                his_guid,
                                REC_GUID,
                                ORDERNO,
                                AGENCYCODE,
                                PRODUCTCODE,
                                BUSINESSTYPE,
                                TRANSTIME,
                                STAFFID,
                                APPLITYPE,
                                APPLINAME,
                                IDENTIFYTYPE,
                                IDENTIFYNUMBER,
                                SEX,
                                BIRTHDATE,
                                MOBILEPHONE,
                                INSUREDNAME,
                                INSUREDTYPE,
                                INSUREDIDENTIFYTYPE,
                                INSUREDIDENTIFYNUMBER,
                                INSUREDSEX,
                                INSUREDBIRTHDATE,
                                INSUREDAPPLIRELATION,
                                STARTDATE,
                                PROJECTCODE,
                                PROJECTNAME,
                                UWCOUNT,
                                OPERATEDATE,
                                ENDDATE,
                                SUMPREMIUM,
                                SUMINSURED,
                                UPDATETIME,
                                tpiChannel,
                                rolegroup_id,
                                companycode,
                                InsuranceConfirmLinkView,
                                InsuranceConfirmLinkEdit,
                                travelArea,
                                buildingAddress,
                                
                                carOwner,
                                carIdentifyType,
                                carIdentifyNumber,
                                licenseNo,
                                seatCount,
                                brandName,
                                FieldBH,
                                frameNo,
                                singeinDate,
                                carValue,
                                useNature
                                )
                          SELECT 
                                sysguid,
                                REC_GUID,
                                ORDERNO,
                                AGENCYCODE,
                                PRODUCTCODE,
                                BUSINESSTYPE,
                                TRANSTIME,
                                STAFFID,
                                APPLITYPE,
                                APPLINAME,
                                IDENTIFYTYPE,
                                IDENTIFYNUMBER,
                                SEX,
                                BIRTHDATE,
                                MOBILEPHONE,
                                INSUREDNAME,
                                INSUREDTYPE,
                                INSUREDIDENTIFYTYPE,
                                INSUREDIDENTIFYNUMBER,
                                INSUREDSEX,
                                INSUREDBIRTHDATE,
                                INSUREDAPPLIRELATION,
                                STARTDATE,
                                PROJECTCODE,
                                PROJECTNAME,
                                UWCOUNT,
                                OPERATEDATE,
                                ENDDATE,
                                SUMPREMIUM,
                                SUMINSURED,
                                UPDATETIME,
                                tpiChannel,
                                rolegroup_id,
                                companycode,
                                InsuranceConfirmLinkView,
                                InsuranceConfirmLinkEdit,
                                travelArea,
                                buildingAddress,
                                 carOwner,
                                carIdentifyType,
                                carIdentifyNumber,
                                licenseNo,
                                seatCount,
                                brandName,
                                FieldBH,
                                frameNo,
                                singeinDate,
                                carValue,
                                useNature
                                FROM EFAMILYINFORMATION  
                                where rec_guid=?
                                     ''';
                jt.update(insertHisSql,rec_guid);

                //更新历史表
                String updateSql='''
                                  Update
                                 EFAMILYINFORMATION
                                Set 
                                ORDERNO= ?,
                                AGENCYCODE= ?,
                                PRODUCTCODE= ?,
                                BUSINESSTYPE= ?,
                                TRANSTIME= ?,
                                STAFFID= ?,
                                APPLITYPE= ?,
                                APPLINAME= ?,
                                IDENTIFYTYPE= ?,
                                IDENTIFYNUMBER= ?,
                                SEX= ?,
                                BIRTHDATE= ?,
                                MOBILEPHONE= ?,
                                INSUREDNAME= ?,
                                INSUREDTYPE= ?,
                                INSUREDIDENTIFYTYPE= ?,
                                INSUREDIDENTIFYNUMBER= ?,
                                INSUREDSEX= ?,
                                INSUREDBIRTHDATE= ?,
                                INSUREDAPPLIRELATION= ?,
                                STARTDATE= ?,
                                PROJECTCODE= ?,
                                PROJECTNAME= ?,
                                UWCOUNT= ?,
                                OPERATEDATE= ?,
                                ENDDATE= ?,
                                SUMPREMIUM= ?,
                                SUMINSURED= ?,
                                UPDATETIME=sysdate,
                                tpiChannel= ?,
                                rolegroup_id=?,
                                UPDATEBY=?,
                                companycode=?,
                                InsuranceConfirmLinkView=?,
                                InsuranceConfirmLinkEdit=?,
                                travelArea=?,
                                buildingAddress=?,
                                  carOwner=?,
                                carIdentifyType=?,
                                carIdentifyNumber=?,
                                licenseNo=?,
                                seatCount=?,
                                brandName=?,
                                FieldBH=?,
                                frameNo=?,
                                singeinDate=?,
                                carValue=?,
                                useNature=?
                                
                                where rec_guid=? 
                                 ''';

                jt.update(updateSql,orderNo,agencyCode,productCode,businessType,transTime,
                        staffid,appliType,appliName, identifyType,identifyNumber,sex,
                        birthDate,mobilePhone,insuredName,insuredType,insuredidentifyType,
                        insuredidentifyNumber,insuredsex,insuredbirthDate, insuredappliRelation,
                        startDate,projectCode,projectName,uwCount,operateDate,endDate,sumPremium,sumInsured,tpiChannel,rolegroupid,staffid,companycode,InsuranceConfirmLinkView,InsuranceConfirmLinkEdit,travelArea,buildingAddress,  carOwner,
                        carIdentifyType,
                        carIdentifyNumber,
                        licenseNo,
                        seatCount,
                        brandName,
                        FieldBH,
                        frameNo,
                        singeinDate,
                        carValue,
                        useNature,rec_guid);



            }else{
                if(businessType.equals("proposalBatchResult")) {
                    for (int b = 0; b < batcharr.size(); b++) {
                        JSONObject dataJson = batcharr.getJSONObject(b);
                        String proposalNo = GetJV(dataJson, "proposalNo");
                        String insertSql2 = '''
                                  INSERT INTO
                                 E_INSURERESULT_LIST
                                (rec_guid,
                                ORDERNO,
                                PROPOSALNO,
                                CREATEDDATE,
                                batch_guid
                                )values(
                                sysguid,
                                ?,
                                ?,
                                sysdate,
                                ?
                                )
                                      ''';
                        jt.update(insertSql2, orderNo, proposalNo,rec_guid);

                    }

                }



                //新单新增入库
                String insertSql='''
                                INSERT INTO
                                 EFAMILYINFORMATION
                                (REC_GUID,
                                ORDERNO,
                                AGENCYCODE,
                                PRODUCTCODE,
                                BUSINESSTYPE,
                                TRANSTIME,
                                STAFFID,
                                APPLITYPE,
                                APPLINAME,
                                IDENTIFYTYPE,
                                IDENTIFYNUMBER,
                                SEX,
                                BIRTHDATE,
                                MOBILEPHONE,
                                INSUREDNAME,
                                INSUREDTYPE,
                                INSUREDIDENTIFYTYPE,
                                INSUREDIDENTIFYNUMBER,
                                INSUREDSEX,
                                INSUREDBIRTHDATE,
                                INSUREDAPPLIRELATION,
                                STARTDATE,
                                PROJECTCODE,
                                PROJECTNAME,
                                UWCOUNT,
                                OPERATEDATE,
                                ENDDATE,
                                SUMPREMIUM,
                                SUMINSURED,
                                UPDATETIME,
                                tpiChannel,
                                rolegroup_id,
                                companycode,
                                InsuranceConfirmLinkView,
                                InsuranceConfirmLinkEdit,
                                CREATEDDATE,
                                CREATEDBY,
                                travelArea,
                                buildingAddress,
                                  carOwner,
                                carIdentifyType,
                                carIdentifyNumber,
                                licenseNo,
                                seatCount,
                                brandName,
                                FieldBH,
                                frameNo,
                                singeinDate,
                                carValue,
                                useNature
                                )
                                values
                                (
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                sysdate,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                sysdate,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?,
                                ?
                                )
                                     ''';

                jt.update(insertSql,rec_guid,orderNo,agencyCode,productCode,businessType,transTime,
                        staffid,appliType,appliName, identifyType,identifyNumber,sex,
                        birthDate,mobilePhone,insuredName,insuredType,insuredidentifyType,
                        insuredidentifyNumber,insuredsex,insuredbirthDate, insuredappliRelation,
                        startDate,projectCode,projectName,uwCount,operateDate,endDate,sumPremium,sumInsured,tpiChannel,rolegroupid,companycode,InsuranceConfirmLinkView,InsuranceConfirmLinkEdit,staffid,travelArea,buildingAddress,  carOwner,
                        carIdentifyType,
                        carIdentifyNumber,
                        licenseNo,
                        seatCount,
                        brandName,
                        FieldBH,
                        frameNo,
                        singeinDate,
                        carValue,
                        useNature);
            }
            result.put("code", 1);
            result.put("message", "处理成功！");
            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'"+orderNo+"','apiEFamilyInformation','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
            eliteBean.update(insertSQL2,'dataSource');



        }catch(Exception e) {
            result.put("code", -1);
            result.put("message", e.getMessage());
            def insertSQL2="insert into fcqt_dm_ifc_log_new(id,ifc_no,send_info,return_info,send_time,return_time) values (Sys_Guid(),'apiEFamilyInformation','" + inData + "','" + result.toString() + "',sysdate,sysdate)";
            eliteBean.update(insertSQL2,'dataSource');
        }
        return result;
    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }



}
